import 'dart:convert';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:xianyu_school/utils/url.dart';
import 'package:xianyu_school/xianyuApp/entity/goods/goods.dart';

class postPage extends StatefulWidget {

  @override
  State<StatefulWidget> createState() {
    return _postPageState();
  }

}

class _postPageState extends State<postPage>{

  String username;
  String _prince;
  String _description;
  String _goodsname;
  goods g = new goods();
  var url = urls().url;
  final _formKey = new GlobalKey<FormState>();
  List<Asset> images = List<Asset>();

  void getusername() async {

    SharedPreferences prefs = await SharedPreferences.getInstance();
    username = prefs.getString("username");

  }

  void _showMessageDialog(String message) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        // return object of type Dialog
        return AlertDialog(
          title: Text('提示'),
          content: Text(message),
          actions: <Widget>[
            FlatButton(
              child: Text("ok"),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  Future<void> post() async {
    final form = _formKey.currentState;
    form.save();
    if (_prince == '') {
      _showMessageDialog('请输入价格');
      return;
    }
    if (_goodsname == '') {
      _showMessageDialog('请输入名称');
      return;
    }
    if (_description == '') {
      _showMessageDialog('请输入描述');
      return;
    }
    g.description = _description;
    g.price = int.parse(_prince);
    g.goodsname = _goodsname;
    Response re = await Dio().post(url+"/goods/add",data: g.toJson());
    if(re.data.toString()=="success"){
      _showMessageDialog('发布成功');
      Navigator.pop(context);
    }
  }

  Widget buildGridView() {
    if (images != null)
      return GridView.count(
        crossAxisCount: 3,
        children: List.generate(images.length, (index) {
          Asset asset = images[index];
          return AssetThumb(
            asset: asset,
            width: 300,
            height: 300,
          );
        }),
      );
    else
      return Container(color: Colors.white);
  }

  @override
  Widget build(BuildContext context) {
    getusername();
    g.username = username;
    return Scaffold(
      appBar: CupertinoNavigationBar(
        backgroundColor: Colors.yellow,
        middle: const Text('发布'),
      ),
      body: Container(
        padding: EdgeInsets.all(10),
        decoration: BoxDecoration(
            shape: BoxShape.rectangle,
            border: Border.all(width: 1, color: Colors.yellow)
        ),
        child: ListView(
          children: [
            Form(
              key: _formKey,
              child: Column(
                children: [
                  TextFormField(
                    maxLines: 5,
                    keyboardType: TextInputType.emailAddress,
                    autofocus: false,
                    style: TextStyle(fontSize: 15),
                    decoration: InputDecoration(
                        border: InputBorder.none,
                        hintText: '说说你的使用感受，入手渠道，转手原因...',
                    ),
                    onSaved: (value) => _description = value.trim(),
                  ),
                  TextFormField(
                    decoration: InputDecoration(
                      icon: Icon(Icons.monetization_on_outlined),
                      labelText: '名称：',
                      labelStyle: TextStyle(color:Colors.black),
                    ),
                    onSaved: (value) => _goodsname = value.trim(),
                  ),
                  TextFormField(
                    keyboardType: TextInputType.number,
                    decoration: InputDecoration(
                      icon: Icon(Icons.monetization_on_outlined),
                      labelText: '价格：',
                      labelStyle: TextStyle(color:Colors.black),
                    ),
                    onSaved: (value) => _prince = value.trim(),
                  ),
                ],
              ),
            ),
            Row(
              children: [
                IconButton(
                    icon: Image.network("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.51yuansu.com%2Fpic2%2Fcover%2F00%2F48%2F03%2F5815d7179c821_610.jpg&refer=http%3A%2F%2Fpic.51yuansu.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1619949655&t=8b1a016dc239674f4032601a3ce01f76"),
                    iconSize: 30,
                    onPressed: () async {
                      String _img = "";
                      try {
                        List<Asset> resultList;
                        resultList = await MultiImagePicker.pickImages(
                          // 选择图片的最大数量
                          maxImages: 3,
                          // 是否支持拍照
                          enableCamera: false,
                          materialOptions: MaterialOptions(
                            // 显示所有照片，值为 false 时显示相册
                              startInAllView: true,
                              allViewTitle: '所有照片',
                              actionBarColor: '#2196F3',
                              textOnNothingSelected: '没有选择照片'
                          ),
                        );
                        setState((){
                          images = resultList;
                        });
                        for(Asset i in resultList){
                          ByteData byteData = await i.getByteData();
                          var buffer = byteData.buffer;
                          var m = base64.encode(Uint8List.view(buffer));
                          _img = _img + m.toString() + ";";
                        }
                        if(!images.isEmpty) g.img=_img;
                      }on Exception catch (e) {
                        e.toString();
                      }
                    }),
              ],
            ),
            Container(
              height: 120,
              child: buildGridView()
            ),
            Row(
              children: [
                Text("分类"),
                Expanded(child: Text(" ")),
                DropdownButton(
                    items: [
                      DropdownMenuItem(child: Text('手机'),value: 1,),
                      DropdownMenuItem(child: Text('电脑'),value: 2,),
                      DropdownMenuItem(child: Text('家电'),value: 3,),
                      DropdownMenuItem(child: Text('书籍'),value: 4),
                      DropdownMenuItem(child: Text('学习用品'),value: 5),
                      DropdownMenuItem(child: Text('母婴玩具'),value: 6,),
                      DropdownMenuItem(child: Text('服饰鞋包'),value: 7,),
                      DropdownMenuItem(child: Text('美妆闲置'),value: 8,),
                      DropdownMenuItem(child: Text('车'),value: 9),
                      DropdownMenuItem(child: Text('其他'),value: 10),
                    ],
                    value: g.classificationid,
                    hint: Text('请选择'),
                    onChanged: (int newvalue){
                      setState(() {
                        g.classificationid = newvalue;
                      });
                    }
                    ),
                Expanded(child: Text(" ")),
                Text("成色"),
                Expanded(child: Text(" ")),
                DropdownButton(
                    items: [
                      DropdownMenuItem(child: Text('几乎全新'),value: '几乎全新',),
                      DropdownMenuItem(child: Text('95新'),value: "95新",),
                      DropdownMenuItem(child: Text('9成新'),value: "9成新",),
                      DropdownMenuItem(child: Text('8成新'),value: "8成新")
                    ],
                    value: g.quality,
                    hint: Text('请选择'),
                    onChanged: (String newvalue){
                      setState(() {
                        g.quality = newvalue;
                      });
                    }
                )
              ],
            ),
            Row(
              children: [
                Expanded(child: Text(" ")),
                OutlineButton(
                    child:Text("发布"),
                    onPressed: () {
                      post();
//                      Navigator.of(context).pop();
                    })
              ],
            )
          ],
        ),
      ),
    );
  }
}